<template>
  <div class="main">
    <div class="headTitle">基本信息</div>
    <commElBasicInfo ref="commElBasicInfo" :basic-information="basicInformation"></commElBasicInfo>
    <div class="styleTabsMain">
      <ul class="styleTabs" style="margin-bottom: 20px;">
        <li @click="toScroll(0, '.module1')" :class="activeTabs === 0 ? 'activeTabs' : ''">交付物</li>
        <li @click="toScroll(1, '.module2')" :class="activeTabs === 1 ? 'activeTabs' : ''">流程设置</li>
      </ul>
      <div class="components-styles-module module1" style="margin-top: 0px;">
        <div class="title">交付物
          <p class="components-styles-module-BtnList">
            <a-button type="primary" @click="addDeliver()"> 添加</a-button>
            <a-button @click="delDeliver()"> 移除</a-button>
          </p>
        </div>
        <div class="main" style="padding-bottom:1px !important;">
          <common-table
            data-row-key="oid"
            :columns="columns" 
            :tableData="tableData"
            :selectType="'checkbox'"
            :isRowsSelectVisible="isRowsSelectVisible"
            @routerPage="routerPage"
            :loadVisible="loadVisible"
            @selectedRows="selectedRows"
            :this-table-name="''">
          </common-table>
        </div>
      <!-- </div>
      <div class="components-styles-module components-styles-module-no module2" style="margin-top: 10px;"> -->
        <p class="title">流程设置</p>
        <div class="main">
          <commonProcessSettings ref="commonProcessSettings" :stateType="'startProjact'" :formData='formData'
                                 :Oid='fileSingleDataC.startSingleID' @fields='fields'></commonProcessSettings>
        </div>
      </div>
    </div>
    <div class="operatingBtnList" style="margin-top: 0px;">
      <a-button @click="cancel()"> 取消</a-button>
      <a-button @click="submit()" type="primary"> 提交</a-button>
    </div>
    <commElFilestartUpload ref="commElFilestartUpload" v-if="isShowUploadFile"
                           @initTableData='initTableData'
                           @callbackData='callbackData'
                           @closeUpFile="closeUpFile"
                           :startType='"callbackData"'
                           :startSingleID='fileSingleDataC'>
    </commElFilestartUpload>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import {
  getAttributeGroup,
  initDocReviewObjsByOids,
  getPageSelectPrincipal,
  startDocWfProcess
} from "@/api/fileSingle.js"
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
import commonTable from '@/views/singleProject/fileSingle/el-common/comm-el-table'
import commonProcessSettings from '@/components/common/commonProcessSettings'
import commElFilestartUpload from '@/views/singleProject/fileSingle/el-common/comm-el-filestart-upload'
import commElBasicInfo from '@/views/singleProject/fileSingle/el-common/conmm-el-basicInformation'
import copyACtion from '@/views/singleProject/fileSingle/el-common-js/copy'
import lodash from 'lodash'
export default {
  mixins: [copyACtion],
  data() {
    return {
      sessionData: {},
      activeTabs: 0,
      isRowsSelectVisible: true,
      loadVisible: false,
      tableSelectArr: [],
      selectedRowKeys: [],
      formData: [],
      columns: [
        {
          displayName: '交付物',
          name: 'name',
          //  scopedSlots: {customRender: "name"}
        },
        {
          displayName: '交付物内容',
          name: 'primaryName',
          scopedSlots: {customRender: "primaryName"}
        },
        {
          displayName: '是否最新版本',
          name: 'isLatestVersion',
        },
        {
          displayName: '交付状态',
          name: 'state',
        },
        {
          displayName: '修改者',
          name: 'modifier',
        },
        {
          displayName: '修改时间',
          name: 'modifyDate',
          dataType: 'Data',
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender"
          }
        },
        {
          displayName: '提交人',
          name: 'creator'
        }],
      tableData: [],
      userOperating: false,
      basicInformation: [],
      isShowUploadFile: false,//是否显示上传交付物
      fileSingleDataByStart: JSON.parse(sessionStorage.getItem('fileSingleDataByStart')),
      // fileSingleDataC: {startSingleID: ''},//xxxx
      fileSingleDataC: JSON.parse(sessionStorage.getItem('fileSingleDataByStart')).tableArr[0]['oid'],
      fileSingleTableItem: JSON.parse(sessionStorage.getItem('fileSingleTableItem')),
    };
  },
  computed: {
    ...mapGetters({
      // 'fileSingleData': 'fileSingle'
    })
  },
  components: {
    commonProcessSettings,
    commonTable,
    commElFilestartUpload,
    commElBasicInfo
  },
  watch: {
    'fileSingleData.tableArr'(val) {
      // this.getBasicInfo()
    }
  },
  mounted() {
    this.getDeliverable(this.fileSingleDataByStart.tableArr)
    this.getProcess()
    this.getBasicInfo()
  },
  methods: {
    /**
     * 获取基本信息
     */
    getBasicInfo() {
      getAttributeGroup({userId: userinfo.loginName, oid: this.fileSingleDataByStart.tableArr[0].oid}).then((res) => {
        if (res && res.data.success) {
          this.basicInformation = res.data.data[0].rows
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    /**
     * 获取交付物列表
     */
    getDeliverable(data) {
      this.loadVisible = true
      let newData = []
      if (this.$store.state.commonData.docTimeData && this.$store.state.commonData.docTimeData.length > 0) {
        newData = lodash.concat(this.$store.state.commonData.docTimeData, data)
      } else {
        newData = data
      }
      let arr = JSON.stringify([...new Set(this.cycleID(newData))])
      initDocReviewObjsByOids({userId: userinfo.loginName, reviewObjOids: arr}).then((res) => {
        this.loadVisible = false
        if (res && res.data.success) {
          let arrs = res.data.data
          this.tableData = arrs.reverse()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    /**
     *
     */
    getProcess() {
      let arr = this.fileSingleDataByStart.tableArr[0]
      for (let key in arr) {
        if (arr[key] === '' || arr[key] === null) {
          delete arr[key]
        }
      }
      getPageSelectPrincipal({
        userId: userinfo.loginName,
        oid: this.fileSingleDataByStart.tableArr[0].oid,
        processName: 'PIDocSignWf',
        type: this.fileSingleDataByStart.tableArr[0].type,
        attributes: JSON.stringify(this.fileSingleDataByStart.tableArr[0])
      }).then((res) => {
        if (res && res.data.success) {
          let optionUser = []
          optionUser = res.data.data[0].selectedUsers
          res.data.data.forEach((item, index) => {
            if (index === 0) return
            this.formData.push({
              name: item.name,
              oid: item.oid,
              required: item.required,
              selsectData: optionUser,
              checkSelsectData: []
            })
            // console.log('formData-----',this.formData)
          })
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    /**
     * commonTable 组件回调方法， val当前点击的哪一行
     */
    routerPage(val) {
      console.log(val)
      this.$store.commit('SET_PROJECT_FILE_TITLE', '')
      // this.$router.push({path: "fileSingle/examineProject"})
    },
    /**
     * 获取table 选择数据
     */
    selectedRows(val) {
      this.tableSelectArr = val
    },
    /**
     * addDeliver 添加交付物 调用公共组件中comm-el-updata
     */
    addDeliver() {
      this.isShowUploadFile = true
      // this.$refs.commElFilestartUpload.openModal(true, 'startFile')
    },
    //关闭弹框
    closeUpFile() {
      this.isShowUploadFile = false
    },
    /**
     * commonProcessSettings 组件回调方法
     * 功能： 提交
     */
    fields(val) {
      let data = {oids: [], processTemplate: 'PIDocSignWf', processUsers: JSON.stringify(val), processState: ''}
      this.tableData.forEach((e)=>{
        data.oids.push(e.oid)
      })
      data.oids = JSON.stringify(data.oids)
      startDocWfProcess(data).then((res) => {
        if (res && res.data.success) {
          this.$message.success('提交成功');
          //跳转至文件树，并关闭文档签审页面
          let tabArrNew = JSON.parse(sessionStorage.getItem('tabArr'))
          tabArrNew = tabArrNew.filter((rec) => {
            return rec.title !== '文档签审' && rec.title !== '查看交付物'
          })
          this.$store.commit('SET_TABS', tabArrNew)
          this.$router.push('/single/fileSingle');
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    /**
     * delDeliver 移除交付物
     */
    delDeliver() {
      let _this = this
      let oidArr = this.cycleID(_this.tableSelectArr)
      if (this.tableSelectArr.length < 1) {
        this.$message.error('请选择您所需要删除的交付物')
        return
      }
      if (oidArr.indexOf(this.tableData[0].oid) !== -1) {
        return this.$message.error('当前主对象不能删除（主对象通常为列表第一条）')
      }
      this.$confirm({
        title: '是否确定移除该交付物？',
        content: '',
        okText: '是',
        okType: 'danger',
        cancelText: '否',
        onOk() {
          oidArr.forEach(item => {
            _this.tableData.forEach((data, index) => {
              if (item === data.oid) {
                _this.tableData.splice(index, 1)
              }
            })
          })
        }
      });
    },
    /**
     * comm-el-filestart-upload 组件回调
     * 功能，通知更新交付物列表
     */
    initTableData() {
      this.getDeliverable()
    },
    callbackData(data) {
      // debugger
      console.log('选择的数据---', data)
      let newData = lodash.concat(this.tableData, data)
      let newDataOids = newData.map((item) => {
        return item.oid
      })//判断是否有相同数据
      let newDataState = newData.map((item) => {
        return item.state
      })
      // console.log('oids---', newDataOids)
      if (new Set(newDataOids).size !== newDataOids.length) {
        this.$message.error('交付物不能重复添加！');
        return
      }
      if (newDataState.toString().indexOf('审阅') > -1 || newDataState.toString().indexOf('发放') > -1 || newDataState.toString().indexOf('作废') > -1) {
        this.$message.error('请添加正在工作/重新工作的文档！');
        return
      }
      this.getDeliverable(newData)
      this.$message.success('添加成功......');
      // this.$refs.commElFilestartUpload.openModal(false)
      this.isShowUploadFile = false
    },
    toScroll(num, key) {
      this.activeTabs = num
      let el = document.querySelector(key)
      el.scrollIntoView()
    },
    submit() {
      this.$refs.commonProcessSettings.handleChange()
    },
    cancel() {
      this.$router.push('/single/fileSingle')
    }
  },
};
</script>
<style lang="less" scoped>
.main {
  background-color: #f0f2f5;
}
.headTitle {
  padding: 20px 0 0 20px;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  box-sizing: border-box;
  background-color: #fff;
}
.components-styles-module-BtnList {
  .ant-btn {
    width: 72px;
    height: 32px;
  }
  .ant-btn-primary {
    margin-right: 10px;
  }
}
.styleTabsMain {
  padding-bottom: 0px;
}
.operatingBtnList {
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 22px;
  height: 56px;
  background: #FFFFFF;
  //box-shadow: 2px 0px 4px 0px rgba(0,0,0,0.2);
  border-radius: 1px;
  box-sizing: border-box;
  .ant-btn {
    margin: 0 5px;
    width: 72px;
    height: 32px;
  }
}
/deep/ .ant-upload,
/deep/ .ant-upload-list {
  margin: auto;
  width: 460px;
}
</style>